package com.kl.drs.service.impl;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URLEncoder;
import java.security.KeyManagementException;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.net.ssl.SSLContext;

import org.apache.commons.io.IOUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.StatusLine;
import org.apache.http.auth.AuthScope;
import org.apache.http.auth.UsernamePasswordCredentials;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.CredentialsProvider;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ssl.NoopHostnameVerifier;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.conn.ssl.TrustStrategy;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.BasicCredentialsProvider;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicHeader;
import org.apache.http.protocol.HTTP;
import org.apache.http.ssl.SSLContextBuilder;
import org.apache.http.util.EntityUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.kl.drs.bean.bo.CheckResultBO;
import com.kl.drs.bean.bo.TaskInfoBO;
import com.kl.drs.bean.dto.TaskDTO;
import com.kl.drs.dao.CheckResultDAO;
import com.kl.drs.dao.TaskInfoDAO;
import com.kl.drs.service.TaskInfoService;
import com.kl.drs.util.ConfigsUtil;
import com.kl.drs.util.DateUtils;
import com.kl.drs.util.Log4jUtils;
import com.kl.drs.util.MD5FileUtil;
import com.kl.drs.util.Md5StringUtil;

@Service("taskInfoService")
public class TaskInfoServiceImpl implements TaskInfoService {
	/*业务信息表*/
	@Autowired
	private TaskInfoDAO taskInfoDAO;
	/*返回值信息表*/
	@Autowired
	private CheckResultDAO checkResultDAO;
	static String protocol=ConfigsUtil.getProperty("zbx.link.protocol");
	static String ip=ConfigsUtil.getProperty("zbx.link.ip");
	static int port=Integer.valueOf(ConfigsUtil.getProperty("zbx.link.port"));
	static HttpHost target = null;	
	/*上传中保信业务信息数据*/
	@Override
	public void uploadTaskRecord(TaskInfoBO taskInfo)
			throws ClientProtocolException, IOException {
		
		CloseableHttpClient httpclient = createSSLClientDefault();
		try {
			HttpClientContext localContext = HttpClientContext.create();
			HttpPost httpPost = new HttpPost(protocol+"://" + ip + ":" + port
					+ "/insurer_task");
			/*
			 * Task task = new Task("1234567890", "李四", "12345678901",
			 * "9146000055277512XL", "110000", "1234567890", 1,
			 * "20171009183302001", "健康险", "ProductA",
			 * "2311199809067788151232311116", "张三", 111, "231181199809067788",
			 * "1990-01-02", "双录信息.mp4", "mp4", "1234", "123456",
			 * "\"9dcbd737305ec6a89878383d22fffdc3\"", 4);
			 */
			TaskDTO task=new TaskDTO();
			task.setCounterid(taskInfo.getCounterId());
			task.setCounterName(taskInfo.getCounterName());
			task.setCounterPhone(taskInfo.getCounterPhone());
			task.setBankCode(taskInfo.getBankCode());
			task.setSubBankCode(taskInfo.getSubBankCode());
			task.setSubInsurerCode(taskInfo.getSubInsurerCode());
			task.setNodeBankCode(taskInfo.getNodeBankCode());
			task.setTaskSource(taskInfo.getTaskSource());
			task.setInsurerCode(taskInfo.getInsurerCode());
			task.setProduct_name(taskInfo.getProductName());
			task.setProduct_code(taskInfo.getProductCode());
			task.setBusinessNo(taskInfo.getBusinessNo());
			task.setCustomerName(taskInfo.getCustomerName());
			task.setCustomerCardType(taskInfo.getCustomerCardType());
			task.setCustomerCardNo(taskInfo.getCustomerCardNo());
			task.setCustomerBirthday(taskInfo.getCustomerBirthday());
			task.setVideoName(taskInfo.getVideoName());
			task.setVideoType(taskInfo.getVideoType());
			task.setBusinessSerialNo(taskInfo.getBusinessSerialNo());
			task.setBatchNo(taskInfo.getBatchNo());
			/*对文件进行MD5操作*/
			/*先获取服务器路径*/
			String vUrl=taskInfo.getVUrl();
			/*路径的拼装*/
			String path=ConfigsUtil.getProperty("video.path", "")+File.separator+vUrl+File.separator+task.getVideoName();
			File trueFile = new File(path);
			String md5=MD5FileUtil.getFileMD5String(trueFile);
			String md5Str="\""+md5+"\"";
			task.setContent_MD5(md5Str);
			task.setPayment_term(taskInfo.getPaymentTerm());
			/*v1.3新增字段*/
			//String recordTime = DateUtils.formatToDate("yyyy-MM-dd HH:mm:ss");
			String recodeTime = taskInfo.getRecordTime();
			if(StringUtils.isNotBlank(recodeTime)){
				task.setRecord_time(DateUtils.formatToDateString(recodeTime));
			}
			task.setFile_time(taskInfo.getFileTime());
			task.setFile_length(taskInfo.getFileLength() / 1024);
			task.setBusinessType(taskInfo.getBusinessType());
			String body = JSON.toJSONString(task);
			httpPost.setHeader("Content-Type", "application/json");
			StringEntity stringEntity = new StringEntity(body, "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE,"application/json;charset=utf8"));
			httpPost.setEntity(stringEntity);
			CloseableHttpResponse response = httpclient.execute(target,httpPost, localContext);
			try {
				Log4jUtils.logDebug("------------------UpdateTask----------------------");
				StatusLine tLine = response.getStatusLine();
				Log4jUtils.logDebug(tLine);
				HttpEntity entity = response.getEntity();
				String data = IOUtils.toString(entity.getContent(), "UTF-8");
				Log4jUtils.logDebug(data);
				if (tLine.getStatusCode() == 200) {
					JSONObject taskObject = JSON.parseObject(data);
					TaskInfoBO taskResult = new TaskInfoBO();
					String bucket = taskObject.getString("bucket");
					String taskId = taskObject.getString("task_id");
					String object = taskObject.getString("object");
					Log4jUtils.logDebug("TaskInfoServiceImpl.uploadTaskRecord(*****object*****)"+ object);
					taskResult.setBusinessNo(taskInfo.getBusinessNo());
					taskResult.setBucket(bucket);
					taskResult.setTaskId(taskId);
					taskResult.setObject(object);
					/*更新数据库，添加返回来的字段信息到数据库*/
					int res = taskInfoDAO.updateTaskInfo(taskResult);
					if (res > 0) {
						Log4jUtils.logDebug("TaskInfoServiceImpl.uploadTaskRecord(更新成功！)");
					} else {
						Log4jUtils.logDebug("TaskInfoServiceImpl.uploadTaskRecord(更新失败！)");
					}
					Log4jUtils.logDebug("TaskInfoServiceImpl.uploadTaskRecord(bucket)"
									+ taskInfo.toString());

					String etag = fileUpload(ConfigsUtil.getProperty("video.path")+File.separator+taskInfo.getVUrl()+File.separator+task.getVideoName(),
							taskObject.getString("bucket"),
							taskObject.getString("object"));
					Log4jUtils.logDebug("------------------上传完成etag" + etag
							+ "----------------------");
					if (!etag.isEmpty()) {
						updateTastStatus(etag, taskObject.getString("task_id"));// 更新任务状态
					}
				}
			} catch (Exception e) {
				
				e.printStackTrace();
				Log4jUtils.logError("UpdateTask.uploadTaskRecord()", "没有成功获取到上传任务返回的对象，上传失败"+e.getMessage(), e);
			} 
		} catch (Exception e){
			Log4jUtils.logError("UpdateTask.uploadTaskRecord()", "上传中保信信息出错，重新检查再上传"+e.getMessage(), e);		
		}finally {
			if(httpclient!=null){
			//	httpclient.close();	
			}
		}

	}

	
	
	/**
	 * 获取授权
	 * @param bucket
	 * @param objectUrl
	 * @return getAuthorization
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private  Map<String, String> getAuthorization(JSONObject jsonObject)
			throws ClientProtocolException, IOException {
			CloseableHttpClient httpclient = createSSLClientDefault();
			HttpClientContext localContext = HttpClientContext.create();
			HttpPut httpPut = new HttpPut(protocol+"://" + ip + ":" + port + "/insurer_getauthor");
			String body = jsonObject.toJSONString();
			httpPut.setHeader("Content-Type", "application/json");
			StringEntity stringEntity = new StringEntity(body, "UTF-8");// 解决中文乱码问题
			stringEntity.setContentEncoding(new BasicHeader(HTTP.CONTENT_TYPE, "application/json;charset=utf8"));
			httpPut.setEntity(stringEntity);
			CloseableHttpResponse response = httpclient.execute(target, httpPut, localContext);
			try {
				Log4jUtils.logDebug("------------------getAuthorization----------------------");
				StatusLine tLine = response.getStatusLine();
				Log4jUtils.logDebug(tLine);
				HttpEntity entity = response.getEntity();
				String data = IOUtils.toString(entity.getContent(), "UTF-8");
				Log4jUtils.logDebug(data);
				if (tLine.getStatusCode() == 200) {
					JSONObject tmpObject = JSON.parseObject(data);
					Map<String, String> tmpMap = new HashMap<String, String>();
					tmpMap.put("url", tmpObject.getString("url"));
					tmpMap.put("method", tmpObject.getString("method"));
					tmpMap.put("host", tmpObject.getString("host"));
					return tmpMap;
						}
					} catch (Exception e) {
						e.printStackTrace();
						Log4jUtils.logError("UpdateTask.uploadTaskRecord.getAuthorization():", "获权失败"+e.getMessage(), e);
						return null;
					}finally{
						if(response!=null){
							response.close();	
						}
						if(httpclient!=null){
						//	httpclient.close();
						}
					}
				return null;
			} 
		
	/**
	 * 上传视频
	 * @param task 
	 * 
	 * @param url
	 * @return
	 * @throws IOException
	 */
	private  String uploadVideo(Map<String, String> tmpMap,String fileName) throws IOException {
		CloseableHttpClient httpclient = createSSLClientDefault();
		HttpPut httpPut = new HttpPut(tmpMap.get("url"));
		httpPut.setHeader("Host", tmpMap.get("host"));
		FileInputStream fInputStream = new FileInputStream(fileName);
		InputStreamEntity inputStreamEntity = new InputStreamEntity(fInputStream);
		httpPut.setEntity(inputStreamEntity);
		CloseableHttpResponse response = httpclient.execute(httpPut) ;
		try {
			
			Log4jUtils.logDebug("-------------------uploadVideo---------------------");
			StatusLine tLine = response.getStatusLine();
			Log4jUtils.logDebug(tLine);
			Log4jUtils.logDebug(response.getFirstHeader("ETag").getValue());
			
			if (tLine.getStatusCode() == 200) {
				String etag = response.getFirstHeader("ETag").getValue();
				return etag;
			} else {
				return "";
			}
		} finally {
			if(fInputStream!=null){
				//fInputStream.close();
			}
			if(response!=null){
				//response.close();
			}
		}
	}
	static CloseableHttpClient httpClient = null;
	/**
	 * 获取受信任httpClient
	 * 
	 * @return
	 */
	private CloseableHttpClient createSSLClientDefault() {
		
		/*获取用户名和密码*/
		String username = ConfigsUtil.getProperty("zbx.connect.username","");
		/*获取加密密码之前*/
		String passwordBefor= ConfigsUtil.getProperty("zbx.connect.password","");
		/*进行密码的加密*/
		String password=Md5StringUtil.string2MD5(passwordBefor);
		
		if (target == null)
			target = new HttpHost(ip, port, protocol);
		if (httpClient != null)
			return httpClient;
		//CloseableHttpClient httpClient = null;
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(new AuthScope(target.getHostName(), target.getPort()),
				new UsernamePasswordCredentials(username, password));
		SSLContext sslContext;
		try {
			sslContext = new SSLContextBuilder().loadTrustMaterial(null,new TrustStrategy(){
				
				 public boolean isTrusted(X509Certificate[] arg0, String arg1){
		                return true;
		            }
			}).build();
			
			SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(sslContext, new String[] { "TLSv1.2"},  
                    null, new NoopHostnameVerifier()); 
			
			httpClient = HttpClients.custom().setSSLSocketFactory(sslsf)
					.setDefaultCredentialsProvider(credsProvider).build();
			return httpClient;
		} catch (KeyManagementException e) {
			
			e.printStackTrace();
		} catch (NoSuchAlgorithmException e) {
			
			e.printStackTrace();
		} catch (KeyStoreException e) {
			
			e.printStackTrace();
		}finally{
			/*关闭连接，释放资源*/
			//httpClient.getConnectionManager();
		}
		return null ;
	}

	/**
	 * 更新任务状态
	 * 
	 * @param etag
	 * @param taskId
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private  boolean updateTastStatus(String etag, String taskId) throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = createSSLClientDefault();
			String enUrl = protocol+"://" + ip + ":" + port + "/insurer_update_task?task_id=" + taskId + "&ETag="
					+ URLEncoder.encode(etag, "UTF-8");
			HttpPost httpPost= new HttpPost(enUrl);
			CloseableHttpResponse response = httpclient.execute(target, httpPost);
			try {
				Log4jUtils.logDebug("-------------------updateTastStatus---------------------");
				StatusLine tLine = response.getStatusLine();
				Log4jUtils.logDebug(tLine);
				HttpEntity entity = response.getEntity();
				String data = IOUtils.toString(entity.getContent(), "UTF-8");
				Log4jUtils.logDebug(data);
				if (tLine.getStatusCode() == 200)
					return true;
				else {
					return false;
				}
			}catch (Exception e ){
				e.getStackTrace();
				Log4jUtils.logError("UpdateTask.uploadTaskRecord.updateTastStatus()","错误提示:"+ e.getMessage(), e);
			}finally{
				if(response!=null){
					response.close();
				}
				if(httpclient!=null){
				//	httpclient.close();
			}
				if(httpPost!=null){
				//	httpPost.releaseConnection();
				}
			
		}
		return false;
	}

	/**
	 * 文件上传
	 * 
	 * @param fileName
	 *            文件名
	 * @param bucket
	 *            桶名称
	 * @param object
	 *            对象名称
	 * @return etag
	 * @throws Exception
	 */
	private  String fileUpload(String fileName, String bucket, String object) throws Exception {
		File tmpFile = new File(fileName);
		long fileLength = tmpFile.length();
		String uploadId = "";
		int fileSize = 5 * 1024 * 1024;
		if (fileLength > fileSize) {
			/*分段上传*/
			return prartVideoUpload(bucket, object, tmpFile, fileLength,
					fileSize);
		} else {
			/*单个上传*/
			JSONObject taskObject = new JSONObject();
			taskObject.put("bucket", bucket);
			taskObject.put("object", object);
			taskObject.put("method", "PUT");
			Map<String, String> tmpMap = getAuthorization(taskObject);// 获取授权
			return uploadVideo(tmpMap, fileName);
		}
	}
	/**
	 * 分段上传封装方法
	 * @param bucket
	 * @param object
	 * @param tmpFile
	 * @param fileLength
	 * @param fileSize
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 * @throws FileNotFoundException
	 */
	private String prartVideoUpload(String bucket, String object, File tmpFile,
			long fileLength, int fileSize) throws ClientProtocolException,
			IOException, FileNotFoundException {
		String uploadId;
		JSONObject taskObject = new JSONObject();
		taskObject.put("bucket", bucket);
		taskObject.put("object", object);
		taskObject.put("method", "POST");
		taskObject.put("subresource", "uploads");
		Map<String, String> tmpMap = getAuthorization(taskObject);// 获取分段上传初始化授权
		uploadId = initPartUploade(tmpMap);
		long tmpValue = fileLength % fileSize;
		if (tmpValue != 0)
			tmpValue = fileLength / fileSize + 1;
		else {
			tmpValue = fileLength / fileSize;
		}
		FileInputStream tmpStream = new FileInputStream(tmpFile);
		Map<Integer, String> fileTags = new HashMap<Integer, String>();
		for (int i = 1; i <= tmpValue; i++) {
			try {
				fileSize = (int) Math.min(fileSize, (fileLength - fileSize * (i - 1)));
				taskObject = new JSONObject();
				taskObject.put("bucket", bucket);
				taskObject.put("object", object);
				taskObject.put("method", "PUT");
				JSONObject subObject = new JSONObject();
				subObject.put("uploadId", uploadId);
				subObject.put("partNumber", i);
				taskObject.put("parameters", subObject);
				tmpMap = getAuthorization(taskObject);// 获取分段上传授权
				byte[] tmpBytes = new byte[fileSize];
				tmpStream.read(tmpBytes);
				String etag = null;
				boolean successFlag = false;
				for (int j = 0; j < 3 && !successFlag; j++) {
					try {
						etag = partVideoUpload(tmpMap, tmpBytes);
						if (!etag.isEmpty()){
							successFlag = true;
						}else{
							successFlag = false;
						}
					} catch (Exception e) {
						Log4jUtils.logError("prartVideoUpload", "分段上传失败" + j, e);
					}
				}
				if (etag == null || etag.isEmpty()) {
					return "上传终止";
				}
				fileTags.put(i, etag);
			} catch (Exception ex) {
				//log.error(ex.getMessage());
				Log4jUtils.logError("prartVideoUpload", "分段上传封装方法:"+ex.getMessage(), ex);
			}

		}

		taskObject = new JSONObject();
		taskObject.put("bucket", bucket);
		taskObject.put("object", object);
		taskObject.put("method", "POST");
		JSONObject subObject = new JSONObject();
		subObject.put("uploadId", uploadId);
		taskObject.put("parameters", subObject);
		/*上传完成*/
		tmpMap = getAuthorization(taskObject);
		/*获取合并分段授权*/
		return completePartVideoUpload(tmpMap, fileTags);
	}

	public static byte[] getBytes(String filePath) {
		byte[] buffer = null;
		try {
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
			byte[] b = new byte[1000];
			int n;
			while ((n = fis.read(b)) != -1) {
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return buffer;
	}

	/**
	 * 分段上传初始化
	 * 
	 * @param tmpMap
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private  String initPartUploade(Map<String, String> tmpMap) throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = createSSLClientDefault();
		HttpPost httpPost = new HttpPost(tmpMap.get("url"));
		httpPost.setHeader("Host", tmpMap.get("host"));
		CloseableHttpResponse response = httpclient.execute(httpPost);
		try {
			Log4jUtils.logDebug("-------------------initPartUploade---------------------");
			StatusLine tLine = response.getStatusLine();
			Log4jUtils.logDebug(tLine);
			if (tLine.getStatusCode() == 200) {
				HttpEntity entity = response.getEntity();
				String data = IOUtils.toString(entity.getContent(), "UTF-8");
				Document document;
				try {
					document = DocumentHelper.parseText(data);
				} catch (DocumentException e) {
					return "";
				}
				Element element = document.getRootElement();
				if (element != null) {
					Element eUploadId = element.element("UploadId");
					String uploadId = eUploadId.getStringValue();
					return uploadId;
				}
				return "";
			} else {
				return "";
			}
		} finally {
			if(response!=null){
				response.close();
			}
			
		}
	}

	/**
	 * 分段上传视频
	 * 
	 * @param tmpMap
	 * @param inputStreamEntity
	 *            输入流
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private  String partVideoUpload(Map<String, String> tmpMap, byte[]tmpBytes)
			throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = createSSLClientDefault();
		InputStreamEntity inputStreamEntity=new InputStreamEntity(new ByteArrayInputStream(tmpBytes));
		HttpPut httpPut = new HttpPut(tmpMap.get("url"));
		httpPut.setHeader("Host", tmpMap.get("host"));
		httpPut.setEntity(inputStreamEntity);
		CloseableHttpResponse response = httpclient.execute(httpPut);
			try {
				Log4jUtils.logDebug("-------------------partVideoUpload---------------------");
				StatusLine tLine = response.getStatusLine();
				Log4jUtils.logDebug(tLine);
				Log4jUtils.logDebug(response.getFirstHeader("ETag").getValue());
				if (tLine.getStatusCode() == 200) {
					String etag = response.getFirstHeader("ETag").getValue();
					return etag;
				} else {
					return "";
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log4jUtils.logError("UpdateTask.uploadTaskRecord.partVideoUpload()", "partVideoUpload:"+e.getMessage(), e);
			}finally{
				if(response!=null){
				response.close();
				}
				
			}
			return "";
		
		}
	String testMethod(CloseableHttpClient httpclient) throws IOException {
		try {
			Thread.sleep(1000);
			httpclient.close();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		return "test";
	}

	/**
	 * 完成分段上传视频
	 * 
	 * @param tmpMap
	 * @param fileTags
	 *            上传的分片集合
	 * @return
	 * @throws ClientProtocolException
	 * @throws IOException
	 */
	private  String completePartVideoUpload(Map<String, String> tmpMap, Map<Integer, String> fileTags)
			throws ClientProtocolException, IOException {
		CloseableHttpClient httpclient = createSSLClientDefault();
		HttpPost httpPost = new HttpPost(tmpMap.get("url"));
		httpPost.setHeader("Host", tmpMap.get("host"));
		Document document = DocumentHelper.createDocument();
		Element root = DocumentHelper.createElement("CompleteMultipartUpload");
		document.setRootElement(root);
		for (int i = 1; i <= fileTags.size(); i++) {
			Element partElement = root.addElement("Part");
			Element partNumElement = partElement.addElement("PartNumber");
			partNumElement.addText(String.valueOf(i));
			Element etagElement = partElement.addElement("ETag");
			etagElement.addText(fileTags.get(i));
		}
		StringEntity sEntity = new StringEntity(document.asXML());
		httpPost.setEntity(sEntity);

		CloseableHttpResponse response = httpclient.execute(httpPost);
		
			try {
				Log4jUtils.logDebug("-------------------completePartVideoUpload---------------------");
				StatusLine tLine = response.getStatusLine();
				if(tLine.getStatusCode() == 200){
					String data = IOUtils.toString(response.getEntity().getContent(), "UTF-8");
					try {
						document = DocumentHelper.parseText(data);
					} catch (DocumentException e) {
						return "";
					}
				}
				Element element = document.getRootElement();
				if (element != null) {
					Element etagEle = element.element("ETag");
					String etag = etagEle.getStringValue();
					return etag;
				}else{
					return "";
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log4jUtils.logError("TaskInfoServiceImpl.uploadTaskRecord.completePartVideoUpload", "上传的分片集合:"+e.getMessage(), e);
			}finally{
				if(response!=null){
					response.close();
				}
			}
			return "";
		
		}
	
	/**
	 * 业务对账
	 */
	@Override
	public boolean checkResultTask(CheckResultBO checkResult) throws Exception {
		/*获取用户名和密码*/
		String username = ConfigsUtil.getProperty("zbx.connect.username","");
		/*获取加密密码之前*/
		String passwordBefor= ConfigsUtil.getProperty("zbx.connect.password","");
		/*进行密码的加密*/
		String password=Md5StringUtil.string2MD5(passwordBefor);
		HttpHost target = new HttpHost(ip, port, protocol);
		CredentialsProvider credsProvider = new BasicCredentialsProvider();
		credsProvider.setCredentials(
				new AuthScope(target.getHostName(), target.getPort()),
				new UsernamePasswordCredentials(username, password));
		CloseableHttpClient httpclient = HttpClients.custom()
				.setDefaultCredentialsProvider(credsProvider).build();
		
			try {
				String httpGetStr = protocol+"://"+ip+":"+port+"/checkResult_task?bankCode="
						
						+ checkResult.getBankCode()
						+ "&subBankCode"
						+ "&businessNo="
						+ checkResult.getBusinessNo()
						+ "&batchNo";
				String httpStr = "\"" + httpGetStr + "\"";
				HttpGet httpGet = new HttpGet(httpGetStr);
				CloseableHttpResponse response = httpclient
						.execute(target, httpGet);
				try {
					String date = EntityUtils.toString(response.getEntity());
					List<HashMap> list = JSON.parseArray(date, HashMap.class);
					for (int i = 0; i < list.size(); i++) {
						/*获取businessNo*/
						Object businessNo = list.get(i).get("businessNo");
						String businessNoStr = (String) businessNo;
						checkResult.setBusinessNo(businessNoStr);
						/*获取businessSerialNo*/
						Object businessSerialNo = list.get(i).get("businessSerialNo");
						String businessSerialNoStr = (String) businessSerialNo;
						checkResult.setBusinessSerialNo(businessSerialNoStr);
						/*获取batchNo*/
						Object batchNo = list.get(i).get("batchNo");
						String batchNoStr = (String) batchNo;
						checkResult.setBatchNo(batchNoStr);
						/*获取bankCode*/
						Object bankCode = list.get(i).get("bankCode");
						String bankCodeStr = (String) bankCode;
						checkResult.setBankCode(bankCodeStr);
						/*获取subBankCode*/
						Object subBankCode = list.get(i).get("subBankCode");
						String subBankCodeStr = (String) subBankCode;
						checkResult.setSubBankCode(subBankCodeStr);
						/*获取subInsurerCode*/
						Object subInsurerCode = list.get(i).get("subInsurerCode");
						String subInsurerCodeStr = (String) subInsurerCode;
						checkResult.setSubInsurerCode(subInsurerCodeStr);
						/*获取taskStatus*/
						Object taskStatus = list.get(i).get("taskStatus");
						int taskStatusInt = (int) taskStatus;
						checkResult.setTaskStatus(taskStatusInt);
						/*获取isCheck*/
						Object isCheck = list.get(i).get("isCheck");
						int isCheckInt = (int) isCheck;

						checkResult.setIsCheck(isCheckInt);
						/*获取checkDate*/
						Object checkDate = list.get(i).get("checkDate");
						String checkDateStr = (String) checkDate;
						checkResult.setCheckDate(checkDateStr);
						/*获取checkResult*/
						Object checkResult1 = list.get(i).get("checkResult");
						String checkResultStr = (String) checkResult1;
						checkResult.setCheckResult(checkResultStr);
						/*获取extented*/
						Object extented = list.get(i).get("extented");
						String extentedStr = (String) extented;
						checkResult.setExtented(extentedStr);
						int res = this.checkResultDAO.updateCheckResult(checkResult);
						if (res > 0) {
							Log4jUtils.logDebug("TaskInfoServiceImpl.checkResultTask(更新成功！)");
							return true;
						} else {
							Log4jUtils.logDebug("TaskInfoServiceImpl.checkResultTask(更新失败！)");
							return true;
						}
					}
				} catch(Exception e){
					Log4jUtils.logError("TaskInfoServiceImpl.checkResultTask()", "--------对账请求失败-------------"+e.getMessage(), e);
					return false;
				}finally{
					if(response!=null){
						response.close();
					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				Log4jUtils.logError("TaskInfoServiceImpl.checkResultTask()", "对账请求:"+e.getMessage(), e);
			} finally{
				if(httpclient!=null){
					httpclient.close();	
				}
			}
			
		return false;

	}

}
